package com.tang.common.interceptor.frequency;

import com.tang.common.exception.GeneralFilterHandlingException;
import com.tang.common.exception.NoRestrictionException;
import com.tang.common.interceptor.AbstractInterceptorHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 初始化并执行拦截器
 * @author tang
 * @date 2022/1/16 12:52
 */
@Slf4j
@Component
public class EntranceFilterHandlerActuator {

    @Autowired
    private List<AbstractInterceptorHandler> abstractInterceptorHandlerList;

    private AbstractInterceptorHandler filterHandler;

    @PostConstruct
    private void init(){
        //初始化拦截器，装填nextAbstractFilterHandler属性
        for (int i = 0; i < abstractInterceptorHandlerList.size(); i++) {
            filterHandler = abstractInterceptorHandlerList.get(i);
            //如果不是最后一个拦截器，则需要设置nextAbstractFilterHandler属性为下一个拦截器
            if (i != abstractInterceptorHandlerList.size() -1){
                filterHandler.setNextAbstractInterceptorHandler(abstractInterceptorHandlerList.get(i + 1));
            }
        }
        //设置从第一个拦截器开始执行
        if (abstractInterceptorHandlerList.size() != 0){
            filterHandler = abstractInterceptorHandlerList.get(0);
        }
    }

    public void actuator(HttpServletRequest request, HttpServletResponse response){
        //如果过拦截器不为空，则开始执行拦截器链路
        if (filterHandler != null){
            try {
                filterHandler.filter(request,response);
            }catch (NoRestrictionException e){
                //无需限制
               log.info(e.getMessage());
            } catch (GeneralFilterHandlingException e){
                //拦截器异常统一处理
                throw new GeneralFilterHandlingException(e.getMessage());
            }

        }
    }

}
